import { useEffect } from 'react';
import {
  DrawerForm,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { useModel } from 'umi';

import request from '@/utils/request';

const titleType = {
  create: '新建仓库',
  edit: '修改仓库',
};

const GroupForm = ({ open, onReloadData, onOpenChange, id, type }) => {
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState.currentUser;
  const isCreate = type === 'create';

  useEffect(() => {
    id &&
      request(`/api/url/${id}`).then((resp) => {
        form.setFieldsValue(resp.data);
      });
  }, [id]);

  const modifyStore = async (values) => {
    const resp = isCreate
      ? await request(`/api/url`, {
          method: 'POST',
          data: values,
        })
      : await request(`/api/url/${values.id}`, {
          method: 'PUT',
          data: values,
        });
    if (isCreate) manualRun(values);
    if (resp.success) {
      message.success(`${titleType[type]}成功!!!`);
      onReloadData();
      isCreate && form.resetFields();
    }
  };

  const manualRun = async (values) => {
    const resp = await request('/api/runComplexity', {
      method: 'POST',
      data: values,
    });
    if (resp.success) message.success('开始检测复杂度……');
  };
  return (
    <DrawerForm
      title={titleType[type]}
      form={form}
      open={open}
      autoFocusFirstInput
      width={600}
      destroyOnClose={true}
      onFinish={async (values) => {
        if (type === 'edit') values.id = id;
        values.username = currentUser.username;
        await modifyStore(values);
      }}
      onOpenChange={(v) => {
        if (v) form.resetFields();
        onOpenChange(v);
      }}
    >
      <ProFormText
        name="name"
        label="仓库名称"
        rules={[{ required: true, message: '请输入 code!' }]}
        placeholder="请输入 name"
      />
      <ProFormTextArea name="desc" label="描述" placeholder="请输入描述" />
      <ProFormText
        name="url"
        label="仓库地址"
        rules={[
          {
            required: true,
            message: '请输入仓库地址!',
          },
          {
            pattern:
              /^(git|https?|ssh):\/\/[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*\.git)$/,
            message: '请输入正确的 git 地址!!!',
          },
        ]}
        disabled={!isCreate}
        placeholder="请输入仓库地址"
      />
    </DrawerForm>
  );
};

export default GroupForm;
